<template>
  <div class="home">
    <jm-head></jm-head>

    <section class="center">
      <!-- quill-editor -->
      <!--<quill-editor ref="myTextEditor"-->
                    <!--v-model="content"-->
                    <!--:config="editorOption"-->
                    <!--@showImageUI="imageHandler">-->
      <!--</quill-editor>-->
      <div id="editor" ref="editor"></div>
      <!-- 必须带上这个input 上传图片用-->
      <input type="file" multiple="multiple" name="file" id="fileinput" accept="image/png,image/gif,image/jpeg" @change="addImg($event)" style="display:none">

        <section class="select_room_box">
          <p><span>你想把该分享发送到哪个空间？</span></p>
          <section class="room_box_item" v-for="item in roomList">
            <input  name="room" type="checkbox" class="room_item" :value="item.id" v-model="checkList"><span>{{item.name}}</span>
          </section>


        </section>
      <!--</div>-->

      <button class="btn" @click="create_post">发布</button>
    </section>


    <jm-fooder></jm-fooder>



  </div>
</template>

<script>
  import JmHead from '../../components/header/Head';
  import JmFooder from '../../components/footer/Footer';
  import Uploader from '../../service/nos-js-sdk';
  import CryptoJS from 'crypto-js'
  import Quill from 'quill'
  import { Toast } from 'mint-ui'

  export default {
    data() {
      return {
        pic_length: 0,  //输入框中已null上传图像的个数
        cover1: "",  //封面一
        cover2: "",  //封面二
        cover3: "",  //封面三
        value: "",
        imgUrl: null,
        content: null,
        roomList:[],  //空间列表
        result: null, //网络请求的结果
        checkList:[],  //选择列表
      }
    },
    components:{
      JmHead,
      JmFooder
    },
    mounted(){
      this.getRoomList();
      this.editor = new Quill('#editor', {
        modules: { toolbar: [
          ['bold', 'italic', 'underline', 'strike'],
          ['blockquote', 'code-block'],
          [{ 'header': 1 }, { 'header': 2 }],
          [{ 'list': 'ordered'}, { 'list': 'bullet' }],
          [{ 'script': 'sub'}, { 'script': 'super' }],
          [{ 'indent': '-1'}, { 'indent': '+1' }],
          [{ 'direction': 'rtl' }],
          [{ 'align': [] }],
          ['clean'],
          ['link', 'image']
        ] },
        placeholder: '说您想说的 ... ...',
        theme: 'snow'
      });
      this.editor.getModule("toolbar").addHandler("image", this.imageHandler);
    },
    watch:{
    },
    computed: {
    },
    methods: {

    // 获取该用户所关注的所有的空间
      async getRoomList(){
        let param = {
          userId: this.$store.state.userInfo.userId,  //用户的id号
          type: -99,  //type start length 都为-99时表示请求用户关注的所有空间列表
          start: -99,
          length: -99,
        }

        let url = '/v1/room?userId=' + this.$store.state.userInfo.userId
          +'&type=-99&start=-99&length=-99'

        await this.axios.get(url)
          .then(response => {
          this.result = response.data;
        })
//        console.log(this.result);
        if (this.result.success){
            this.roomList = this.result.result;
        }else{
          let instance = Toast({message: '网络连接失败', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
        }
      },

      onEditorChange({editor, html, text}) {
        this.content = html;
      },


      imageHandler() {
        let fileinput = document.getElementById('fileinput');
        fileinput.click()
      },

      addImg() {
        let fileinput = document.getElementById('fileinput');
        let i = 0;
        for(; i < fileinput.files.length; i ++){
          let image = fileinput.files[i]

          let reader = new FileReader();
          reader.readAsBinaryString(image);

          reader.onload = function (e) {
            let name = CryptoJS.MD5(e.target.result)+'.jpg';
            this.uploadImg(image, name);
          }.bind(this);
        }

      },

      addImgToContent(fileName){
            let imageUrl = this.$store.state.baseImgUrl+fileName;
            let range = this.editor.getSelection();
            let length = range.index;
            this.editor.insertEmbed(length, 'image', imageUrl);
      },

      uploadImg(image, fileName){
        let that = new Uploader();
          let param = {
            bucketName: 'jimikongjian',
            objectName: fileName,
            token: this.getToken(fileName),
            trunkSize: 4 * 1024 * 1024,
          }


          if (image) {
            that.addFile(image, function(curFile){
              console.log(curFile.fileName + ' is added.');
            });
            that.upload(param, function(curFile){
              console.log('File: ' + curFile.fileName + ' is uploaded.');
              this.addImgToContent(fileName);
            }.bind(this));

          }

      },


    //获取上传凭证
      getToken(Object){
        let p = {
          "Bucket" : "jimikongjian",
          "Object" : Object,
          "Expires" : this.$store.state.expiresTime
        }
        let putPolicy = JSON.stringify(p);
        let wordArray = CryptoJS.enc.Utf8.parse(putPolicy);
        let encodedPutPolicy = CryptoJS.enc.Base64.stringify(wordArray);
        let sign = CryptoJS.HmacSHA256(encodedPutPolicy, this.$store.state.accessSecret);
        let encodedSign = CryptoJS.enc.Base64.stringify(sign);
        return "UPLOAD " + this.$store.state.accessKey + ":" + encodedSign + ":" + encodedPutPolicy;
      },



      getCover(text){
        let re = new RegExp("<img([^<>]*)>([^<>]*)", "g");
        let r = text.match(re); // 在字符串 s 中查找匹配。
        let i = 0;
        for (; r && i < r.length && i < 3 ; i ++){

            if (i === 0){
                this.cover1 = r[0].substring(10, r[i].length-2);

            }
            if (i === 1){
                this.cover2 = r[1].substring(10, r[i].length-2);
            }
            if (i === 2){
                this.cover3 = r[2].substring(10, r[i].length-2);
            }
        }
      },

      getTitle(text){

        let re = new RegExp("^<h.([^<>]*)>([^<>]*)<\/h.>", "g");
        let r = text.match(re); // 在字符串 s 中查找匹配。

          // 去掉img标签
          let contentValue1 = this.$refs.editor.children[0].innerHTML.replace(/<img\b[^>]*>/g, "");
          //去掉头标签
          let contentValue2 = contentValue1.replace(/^<h.([^<>]*)>([^<>]*)<\/h.>/g, "");
          // 去掉所有的html标签
          let contentValue3 = contentValue2.replace(/<[^>]+>/g, "");


          if (contentValue3.length < 100){
              if (r !== null){
                return  r+"<p>"+contentValue3+"</p>";
              }else {
                return  "<p>"+contentValue3+"</p>";
              }

          }else{
              if (r !== null){
                return r+"<p>"+contentValue3.substring(0, 100)+"</p>";
              }else{
                return "<p>"+contentValue3.substring(0, 100)+"</p>";
              }

          }

      },

      create_post(){
        this.getCover(this.$refs.editor.children[0].innerHTML);
        let i = 0;
        if (typeof(this.checkList[0])=="undefined" || this.checkList.length < 0){
            let instance = Toast({message: '请选择分享的空间', className: 'toast'});
            setTimeout(() => {
              instance.close();
            }, 2000);

        }else if (this.$refs.editor.children[0].innerHTML.length == 11){
          let instance = Toast({message: '请填写你分享的内容', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
        }else{


          let param = {
            author: this.$store.state.userInfo.userId,
            authorNick: this.$store.state.userInfo.nick,
            title: this.getTitle(this.$refs.editor.children[0].innerHTML),
            content: this.$refs.editor.children[0].innerHTML,
            upvoteCount: 0,
            commentCount: 0,
            likeCount: 0,
//            roomList: JSON.stringify(this.checkList),
            roomList: this.checkList,
            value: 0,
            cover1: this.cover1,
            cover2: this.cover2,
            cover3: this.cover3,
          }

          let res = null;

          this.axios.post('/v1/article', param)
            .then(response => {
              res = response.data;
            });

          if (res.success){
            let instance = Toast({message: '分享成功', className: 'toast'});
            setTimeout(() => {
              instance.close();
              this.$router.push('home');
            }, 2000);

          }else{
            let instance = Toast({message: '网络连接失败', className: 'toast'});
            setTimeout(() => {
              instance.close();
            }, 2000);
          }


        }


      }

    },
    computed: {
    },
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
  .ql-container{
    height: 350px;
  }
  /*.ql-snow.ql-toolbar button, .ql-snow .ql-toolbar button{
    height: 0.8rem;
    width: 0.8rem;
  }
  .ql-snow .ql-color-picker, .ql-snow .ql-icon-picker{
    height: 0.8rem;
    width: 0.8rem;
  }*/
  .ql-editor{
    font-size: 0.6rem;
  }
  .mint-toast-text{
    font-size: 0.6rem;
  }

  .toast{
    min-width: 20%;
    width: 20%;
    span{
      color: #FFFFFF;
    }
  }
</style>
<style lang="scss" scoped>
  @import '../../style/mixin';


  .center{
    padding-top: 1.3rem;
    padding-bottom: 2rem;
    overflow: hidden;
  }

  .selectRoom{
    margin: 1rem 0.5rem;
  }

  .btn{
    margin: 0 auto;
    display: block;
    background-color: #33CCFF;
    width: 9rem;
    height: 1.4rem;
    color: #FFFFFF;
    font-size: 0.5rem;
    font-weight: bold;
    @include borderRadius(0.7rem);
    margin-top: 1rem;
    margin-bottom: 1rem;
  }

  .select_room_box{
    width: 100%;
    padding: 0 0.5rem;
    padding-top: 0.5rem;
    font-size: 0.6rem;

    .room_box_item{
      display: inline-block;
      margin: 0.1rem;

      .room_item{
        margin: 0.1rem 0.2rem;
        width: 0.6rem;
      }
    }


  }




</style>
